﻿using Microsoft.Extensions.DependencyInjection;
using Niaofei.Application.Contracts;
using Niaofei.Domain;
using Niaofei.Injcetion;

namespace Niaofei.Application
{
    [Injection(typeof(ISysRoleAppService))]
    internal class SysRoleAppService : NiaofeiAppService, ISysRoleAppService
    {
        private readonly ISysRoleRepository _sysRoleRepository;

        public SysRoleAppService(IServiceProvider serviceProvider) : base(serviceProvider)
        {
            _sysRoleRepository = serviceProvider.GetRequiredService<ISysRoleRepository>();
        }

        public async Task<ResultDto<SysRoleDto>> AddSysRole(SysRoleDto input)
        {
            var entity = Mapper.Map<SysRoleDto, SysRole>(input);

            entity = await _sysRoleRepository.InsertAsync(entity);

            var result = Mapper.Map<SysRole, SysRoleDto>(entity);

            return new ResultDto<SysRoleDto>(result);
        }

        public async Task<ResultDto<string>> DeleteSysRole(List<int> ids)
        {
            var entitys = (await _sysRoleRepository.GetQueryableAsync())
                .Where(m => ids.Contains(m.Id))
                .ToList();

            await _sysRoleRepository.DeleteManyAsync(entitys);

            return new ResultDto<string>() { Code = "0", Data = "成功" };
        }

        public async Task<ResultDto<PageOutputDto<SysRoleDto>>> GetSysRolePage(SysRoleInputDto input)
        {
            var query = (await _sysRoleRepository.GetQueryableAsync())
                .WhereIf(!string.IsNullOrEmpty(input.Name), m => m.Name.Contains(input.Name))
                .OrderBy(m => m.Sort);

            var count = query.Count();

            var list = query.Skip((input.PageNo - 1) * input.PageSize).Take(input.PageSize).ToList();

            var result = Mapper.Map<List<SysRole>, List<SysRoleDto>>(list);

            return new ResultDto<PageOutputDto<SysRoleDto>>(new PageOutputDto<SysRoleDto>(count, result));
        }

        public async Task<ResultDto<List<SysRoleDto>>> GetSysRole()
        {
            var list = (await _sysRoleRepository.GetQueryableAsync())
                .OrderBy(m => m.Sort).ToList();

            var result = Mapper.Map<List<SysRole>, List<SysRoleDto>>(list);

            return new ResultDto<List<SysRoleDto>>(result);
        }

        public async Task<ResultDto<SysRoleDto>> UpdateRole(SysRoleDto input)
        {
            var entity = (await _sysRoleRepository.GetQueryableAsync())
                .FirstOrDefault(m => m.Id == input.Id);

            if (entity == null)
            {
                return new ResultDto<SysRoleDto>("数据不存在！");
            }

            Mapper.Map(input, entity);

            entity = await _sysRoleRepository.UpdateAsync(entity);

            input = Mapper.Map<SysRole, SysRoleDto>(entity);

            return new ResultDto<SysRoleDto>(input);
        }
    }
}
